import logging

from django.core.cache import cache
from django.http import JsonResponse
from django.views import View

from areas.models import Area
from meiduo.utils.views import LoginRequiredMixin

logger = logging.getLogger("django")

# Create your views here.


class ProvinceAreasView(LoginRequiredMixin, View):

    def get(self, request):
        """
        获取所有省份
        :param request: 请求对象
        :return: JSON
        """
        '''获取省份数据'''
        province_list = cache.get("province_list")  # 读取缓存
        if not province_list:  # 检查是否有缓存
            province_list = []
            province_model_list = Area.objects.filter(parent_id__isnull=True)  # parent_id=Null的地区皆为省级地区
            for province in province_model_list:  # 整理省份数据
                province_list.append({"id": province.id, "name": province.name})
            cache.set("province_list", province_list, 3600)  # 缓存省份数据1小时

        '''返回省份数据'''
        return JsonResponse({
            "code": 0,
            "errmsg": "OK",
            "province_list": province_list
        })


class SubAreasView(View):

    def get(self, request, pk):
        """
        获取省对应的所有市，或市对应的所有区
        :param request: 请求对象
        :param pk: 省或市的主键(id)
        :return: JSON
        """
        '''获取市级或区级数据'''
        sub_data = cache.get(f"sub_data_{pk}")  # 读取缓存
        if not sub_data:  # 检查是否有缓存
            '''获取上级信息'''
            try:
                province = Area.objects.get(id=pk)  # 通过主键获取上级对象，以获取其id和名称
            except Exception as e:
                logger.error(e)
                return JsonResponse({"code": 400, "errmsg": "获取省或市的信息失败"})
            sub_data = {
                "id": pk,  # 上级id
                "name": province.name,  # 上级名称
                "subs": None  # 上级所属市或区，即当前所要获取的数据
            }

            '''获取对应的市或区'''
            subs = []
            city_list = Area.objects.filter(parent_id=pk)  # 获取pk对应的所有市或区
            for city in city_list:  # 整理数据
                subs.append({"id": city.id, "name": city.name})
            sub_data["subs"] = subs
            cache.set(f"sub_data_{pk}", sub_data, 3600)  # 缓存数据1小时

        '''返回数据'''
        return JsonResponse({
            "code": 0,
            "errmsg": "OK",
            "sub_data": sub_data
        })

